package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.JwtUtils;
import com.qk.domain.user.UserDO;
import com.qk.dto.user.UserDTO;
import com.qk.dto.user.UserLoginDTO;
import com.qk.entity.Role;
import com.qk.entity.User;
import com.qk.management.mapper.RoleMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.UserService;
import com.qk.vo.user.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * &#064;author：zzq
 * &#064;createTime：2025/10/07 18:16
 * &#064;description： 用户管理实现类
 *
 */
@Service
public class UserServiceImpl implements UserService {
    private static final String DEFAULT_PASSWORD_SUFFIX = "123";
    private static final Integer USER_STATUS_ABNORMAL = 0;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void add(User user) {
        // 参数校验： 工具类处理 hutool 工具类
        boolean hasNull = BeanUtil.hasNullField(user, "id", "password", "roleId", "deptId", "image", "remark", "updateTime", "createTime");
        if (hasNull) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        // 补全数据
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        // 设置默认密码
        String rawPassword = user.getUsername() + DEFAULT_PASSWORD_SUFFIX;
        //MD5算法对原始密码进行消息摘要处理得到字符串
        String encodedPassword = DigestUtils.md5DigestAsHex(rawPassword.getBytes());
        user.setPassword(encodedPassword);
        // 插入
        userMapper.insert(user);
    }

    @Override
    public void deleteBatch(List<Integer> ids) {
        //数据校验
        boolean isNotEmpty = CollectionUtil.isNotEmpty(ids);
        if (!isNotEmpty) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        //批量删除
        userMapper.deleteBatch(ids);
    }

    @Override
    public UserDO get(Integer id) {
        return userMapper.get(id);
    }

    @Override
    public void update(User user) {
        boolean hasNull = BeanUtil.hasNullField(user, "id", "password", "roleId", "deptId", "image", "remark", "updateTime", "createTime");
        if (hasNull) {
            throw new RuntimeException("参数错误");
        }
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }

    @Override
    public List<UserDO> listByRole(String roleLabel) {
        return userMapper.listByRole(roleLabel);
    }

    @Override
    public UserLoginVO login(UserLoginDTO dto) {
        //1.参数合法性校验
        boolean hasNull = BeanUtil.hasNullField(dto);
        if (hasNull) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        //2.根据用户名获取用户对象
        User dbUser = userMapper.selectByUsername(dto.getUsername());
        //3.判断用户对象是否为空
        if (Objects.isNull(dbUser)) {
            CommonException.throwCommonException(ParamEnum.USER_NOT_EXIST);
        }
        //3.1 判断用户状态是否正常
        if (ObjectUtil.equal(dbUser.getStatus(), USER_STATUS_ABNORMAL)) {
            CommonException.throwCommonException(ParamEnum.USER_STATUS_ERROR);
        }
        //4.判断密码是否一致
        String userPassword = DigestUtils.md5DigestAsHex(dto.getPassword().getBytes());
        String encodedPassword = dbUser.getPassword();
        boolean isChecked = ObjectUtil.equal(encodedPassword, userPassword);
        if (!isChecked) {
            CommonException.throwCommonException(ParamEnum.USER_PASSWORD_ERROR);
        }
        //5.返回用户信息
        //5.1根据角色id查询角色名称
        Role role = roleMapper.selectById(dbUser.getRoleId());
        //生成令牌中需要携带自定义信息
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", dbUser.getId());
        claims.put("username", dbUser.getUsername());
        String token = JwtUtils.generateToken(claims);
        return UserLoginVO.builder()
                .id(dbUser.getId())
                .username(dbUser.getUsername())
                .name(dbUser.getName())
                .image(dbUser.getImage())
                .roleLabel(role.getLabel())
                .token(token)
                .build();
    }

    @Override
    public PageResult<UserDO> list(UserDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<UserDO> result = userMapper.selectByPage(dto);

        // 对电话号码进行脱敏处理
        result.forEach(userDO -> {
            if (userDO.getPhone() != null) {
                userDO.setPhone(cn.hutool.core.util.DesensitizedUtil.mobilePhone(userDO.getPhone()));
            }
        });

        Page<UserDO> page = (Page<UserDO>) result;
        return PageResult.<UserDO>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(page.getResult())
                .build();
    }

}
